package com.example.keli.base.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.keli.R;
import com.example.keli.api.RetrofitManager;
import com.example.keli.base.BaseApplication;
import com.example.keli.ui.my.model.OrderVO;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;

/**
 * description $desc$
 * created by jerry on 2019/3/26.
 */
public class PayUtil {
    //赠送礼物
    public static void wechatPayGift(final Context context, String gid, String num, String by_uid, String act, String aaid) {
        final WebView webView = getWebView(context);
        Map<String, String> map = new HashMap<>();
        map.put("gid", gid);
        map.put("num", num);
        map.put("by_uid", by_uid);
        map.put("act", act);
        map.put("aaid", aaid);
        RetrofitManager.ApiFunc(RetrofitManager.mApiService.setTicket(map), new SubscriberListener<BaseResponse<OrderVO>>() {
            @Override
            public void onSuccess(BaseResponse<OrderVO> orderVOBaseResponse) {
                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Referer", "http://keli.fz222.com");
                EventBus.getDefault().post(orderVOBaseResponse.data);
                webView.loadUrl(orderVOBaseResponse.data.getMweb_url(), extraHeaders);
            }

            @Override
            public void onFailer(String msg) {
//                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    //赠送专属礼物，送出即可加微信
    public static void wechatPayOnlyGift(final Context context, String by_uid, String aaid, String act) {
        final WebView webView = getWebView(context);
        Map<String, String> map = new HashMap<>();
        map.put("by_uid", by_uid);
        map.put("aaid", aaid);
        map.put("act", act);
        RetrofitManager.ApiFunc(RetrofitManager.mApiService.setGift(map), new SubscriberListener<BaseResponse<OrderVO>>() {
            @Override
            public void onSuccess(BaseResponse<OrderVO> orderVOBaseResponse) {
                Map<String, String> extraHeaders = new HashMap<String, String>();
                extraHeaders.put("Referer", "http://keli.fz222.com");
                EventBus.getDefault().post(orderVOBaseResponse.data);
                webView.loadUrl(orderVOBaseResponse.data.getMweb_url(), extraHeaders);
            }

            @Override
            public void onFailer(String msg) {
//                ToastUtil.show(msg);
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    @NonNull
    private static WebView getWebView(final Context context) {
        final WebView webView = new WebView(context);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient() {
            private Dialog dialog;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                dialog = DialogUtil.getCenterProgressDialog(BaseApplication.getAppContext().getCurActivity());
                if (dialog != null){
                    dialog.show();
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (dialog != null){
                    dialog.dismiss();
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                LogUtils.loge("url:"+url);
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    context.startActivity(intent);
                    return true;
                } else {
                    Map<String, String> extraHeaders = new HashMap<String, String>();
                    extraHeaders.put("Referer", "http://keli.fz222.com");
                    view.loadUrl(url, extraHeaders);
                }
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) { // 重写此方法可以让webview处理https请求
                handler.proceed();
            }
        });

        return webView;
    }

    public static void showPayResultDailog(Activity activity, boolean success){
        View view = activity.getLayoutInflater().inflate(R.layout.pay_result_dialog,null);
        ImageView iv_result = view.findViewById(R.id.iv_result);
        TextView tv_result = view.findViewById(R.id.tv_result);
        ImageView iv_close = view.findViewById(R.id.iv_close);
        final Dialog dialog = DialogUtil.whiteCenterDialog(activity, view);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null){
                    dialog.dismiss();
                }
            }
        });

        tv_result.setText(success?"支付成功":"支付失败");
        iv_result.setImageResource(success?R.mipmap.pay_success:R.mipmap.pay_failer);
        dialog.show();
    }

}
